package com.example.springmall.service;

import com.example.springmall.dto.LoginResponse;
import com.example.springmall.entity.SysUser;
import com.example.springmall.exception.BusinessException;
import com.example.springmall.exception.UnauthorizedException;
import com.example.springmall.mapper.SysUserMapper;
import com.example.springmall.mapper.SysUserRoleMapper;
import com.example.springmall.request.LoginRequest;
import com.example.springmall.util.JwtUtil;
import com.example.springmall.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class UserService {

    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;

    public LoginResponse login(LoginRequest loginRequest) {
        // 1. 验证用户名和密码
        SysUser user = sysUserMapper.selectByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new UnauthorizedException("用户名错误");
        }
        if (!user.getPassword().equals(MD5Util.encrypt(loginRequest.getPassword()))) {
            throw new UnauthorizedException("密码错误");
        }

        // 2. 获取用户角色
        String roleCode = sysUserRoleMapper.selectRoleCodeByUserId(user.getId());
        
//        // 3. 验证用户选择的角色是否匹配
//        if (!roleCode.equals(loginRequest.getRoleCode())) {
//            throw new UnauthorizedException("您没有该角色的登录权限");
//        }

        // 4. 生成token
        String token = JwtUtil.generateToken(user.getId());

        // 5. 构建返回对象
        LoginResponse response = new LoginResponse();
        response.setToken(token);

        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setRealName(user.getRealName());
        response.setEmail(user.getEmail());
        response.setPhone(user.getPhone());
        response.setRoleCode(roleCode);

        return response;
    }

    @Transactional
    public void register(SysUser sysUser) {
        // 1. 检查用户名是否已存在
        if (sysUserMapper.getByUsername(sysUser.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }

        // 2. 设置用户状态为正常
        sysUser.setStatus(1);

        // 3. 保存用户信息
        sysUserMapper.register(sysUser);

        // 4. 为新用户分配普通用户角色（角色ID为2）
        sysUserMapper.insertUserRole(sysUser.getId(), 2L);
    }
} 